<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索区域 -->
      <div class="search">
        <el-input placeholder="请输入搜索id" v-model="input" clearable prefix-icon="el-icon-search" @clear="getList"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="getList">搜索</el-button>
      </div>
      <!-- 用户列表区域 -->
      <el-table :data="tableData" stripe border style="width:100%;">
        <el-table-column label="ID" prop="id" width="80"></el-table-column>
        <el-table-column label="用户名" prop="user" width="120"></el-table-column>
        <el-table-column label="密码" prop="password" width="80"></el-table-column>
        <el-table-column label="用户头像" prop="img" width="120">
          <template slot-scope="scope">
            <img :src="scope.row.img" alt class="imgs" />
          </template>
        </el-table-column>
        <el-table-column label="性别" prop="gender" width="80">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.gender=='1'">男生</el-tag>
            <el-tag type="danger" v-else>女生</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="积分" prop="inte" width="80"></el-table-column>
        <el-table-column label="余额" prop="money" width="80"></el-table-column>
        <el-table-column label="修改时间" prop="time">
          <template slot-scope="scope">
            <span v-if="scope.row.time=='0000-00-00 00:00:00'">{{1598690950491|dateFormat}}</span>
            <span v-else>{{scope.row.time | dateFormat}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
              <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="update(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
              <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="detail(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <page @down="change" @up="changes" :list="tableData1"></page>
    </el-card>
    <!-- 修改用户信息对话框 -->
    <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="600px" :before-close="handleClose">
      <el-form ref="form" :model="addform" label-width="80px" :rules="addformRules" class="demo-ruleForm" :label-position="labelPosition">
        <el-form-item label="用户昵称" prop="user" class="items">
          <el-input v-model="addform.user" style="width:350px;"></el-input>
        </el-form-item>
        <el-form-item label="原密码" prop="password" class="items">
          <el-input type="password" v-model="password" style="width:350px;" @blur="pass()" placeholder="请输入原密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" class="items">
          <el-input type="password" style="width:350px;" v-model="password1" @blur="pass1()" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="性别" class="items">
          <el-select v-model="addform.gender" placeholder="请选择性别" style="width:350px;">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户头像" class="items">
          <el-upload action="/img/" list-type="picture-card" :limit="1" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handles" :file-list="fileList">
            <i class="el-icon-plus"></i>
            <!-- <i class="el-icon-delete" v-show="addForm.img" @click.stop="handleRemove3"  id="ims"></i>
                   <i   class="el-icon-plus avatar-uploader-icon"  v-show="addForm.img" id="ims"></i>
                  <img v-if="addForm.img" :src="addForm.img.split(',')[0]" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUpdate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import page from '@/components/pagesize.vue'
import axi from '@/utils/text.js'
export default {
  inject: ['reload'],
  data() {
    var validatePass = (rule, value, callback) => {
      //  console.log(this.flag, '方形了没')
      setTimeout(() => {
        if (!this.flag) {
          this.yx = false
          //     console.log('不争取')
          callback(new Error('额原密码不正确'))
        } else {
          this.yx = true
          //   if (this.ruleForm.checkPass !== '') {
          //     this.$refs.ruleForm.validateField('checkPass');
          //   }
          callback()
        }
      }, 500)
    }
    return {
      input: '',
      yx: true,
      password: '', // 原密码
      password1: '', // 新密码
      labelPosition: 'right',
      tableData1: [],
      tableData: [],
      dialogFormVisible: false,
      addform: {
        user: '',
        password: '',
        img: '',
        gender: '',
        id: ''
      },
      flag: false,
      formLabelWidth: '60px',
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: [],
      // 表单校验规则
      addformRules: {
        user: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: this.cl() }]
      }
    }
  },
  created() {
    this.getList()
    this.times()
  },
  mounted() {
    this.fileList = []
  },
  methods: {
    async  getList() {
      if (this.input) {
        this.$http.post('/dev/user/admin', { id: this.input }).then(res => {
          this.tableData1 = res.data.message.reverse()
          this.tableData = this.tableData1.slice(0, 10)
        })
      } else {
        const res = await axi.getAllPost('/user/admin', 'post')
        this.tableData1 = res.data.message.reverse()
        this.tableData = this.tableData1.slice(0, 10)
      }
    },
    change(num1) {
      this.tableData = num1
    },
    changes(num1) {
      this.tableData = num1
    },
    // 删除用户事件
    detail() {
      this.$message.warning('哦豁,您没有权限')
    },
    cl() {
      // this.flag=!this.flag
      //  console.log(console.log(this.flag))
    },
    // 修改事件
    async update(id) {
      this.fileList = []
      const res = await axi.getAllPost('/user/admin', 'post', { id: id })
      this.addform = res.data.message[0]
      if (res.data.message[0].img) {
        const a = [{ url: res.data.message[0].img }]
        this.fileList = a
      }
      this.dialogFormVisible = true
    },
    async addUpdate() {
      // console.log(this.addform)
      const configmResult = await this.$confirm('此操作将修改用户数据,是否继续', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (configmResult !== 'confirm') {
        this.$message.info('已取消修改')
        this.dialogFormVisible = false
      } else {
        if (this.addform.password.trim() === '**') {
          this.addform.password = ''
        }
        // this.dialogFormVisible=false
        if (this.password1.trim()) {
          // console.log('我没有修改密码')
          this.addform.password = this.password1.trim()
          this.yx = !this.yx
        } else {
          delete this.addform.password
          this.yx = false
        }
        // console.log(this.addform)
        this.addform.time = this.times()
        // console.log(this.flag, this.yx, 'yx')
        if (this.yx) {
          this.pass()
          this.$message.warning('请输入原密码')
        } else {
          //   console.log('没有修改密码')
          // this.addform.id=String(this.addform.id)
          this.dialogFormVisible = false
          console.log(this.addform)
          const data = {
            id: this.addform.id,
            user: this.addform.user,
            img: this.addform.img,
            password: this.addform.password,
            time: this.addform.time
          }
          this.$http.post('/user/admin/update', data, {
            headers: {
              'Content-Type': 'application/json; charset=utf-8'
            }
          }).then(res => {
            console.log(res)
            if (res.data.err_code === 0) {
              this.$message.success('修改成功')
              this.getList()
              this.reload()
            }
          })
        }
      }
    },
    times() {
      const dt = new Date(+new Date())
      const y = dt.getFullYear()
      const m = (dt.getMonth() + 1 + '').padStart(2, '0')
      const d = (dt.getDate() + '').padStart(2, '0')
      const hh = (dt.getHours() + '').padStart(2, '0')
      const mm = (dt.getMinutes() + '').padStart(2, '0')
      const ss = (dt.getSeconds() + '').padStart(2, '0')
      //  console.log(`${y}-${m}-${d} ${hh}-${mm}-${ss}`)
      return `${y}-${m}-${d} ${hh}-${mm}-${ss}`
    },

    // 确定修改
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.fileList = []
        })
        .catch(_ => { })
    },
    // 预览图片事件
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    // 移除图片事件
    handleRemove() { },
    // 上传图片成功事件
    handles(file) {
      this.addform.img = file.data
    },
    // 校验密码
    pass() {
      const data = {
        id: this.addform.id,
        password: this.password
      }
      this.$http.post('/user/admin/password', data).then(res => {
        //  console.log(res)
        if (res.data.err_code === 400) {
          this.flag = false
          //  console.log(this.flag)
          this.$refs.form.validateField('password')
        } else if (res.data.err_code === 200) {
          this.flag = true
          //  console.log(this.flag)
        }
      })
      //  console.log(this.addform.password)
    },
    pass1() {
      if (!this.flag) {
        this.pass()
      }
    }
  },

  components: {
    page
  },
  watch: {
    flag(val) {
      this.flag = val
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.el-input__inner {
  // margin-right: 425px!important;
  // margin-left: -125px!important;
}
/deep/.el-input .el-input--suffix {
  // margin-left: -125px!important;
}
.items {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
/deep/.imgs {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  padding: 0;
  border: 0 solid #fff;
}
/deep/.el-table_1_column_4 {
  padding: 0;
}
.search {
  height: 50px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  line-height: 50px;
  .el-input {
    width: 350px;
    margin: 0 15px 0 0;
  }
  .el-button {
    margin-top: 5px;
    height: 40px;
  }
}
</style>
